<template>
  <div class="app">
    <router-view />
  </div>
</template>

<script setup lang="ts">
import { watch, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/stores/useUserStore'
import wsClient from '@/utils/websocket'

const userStore = useUserStore()
let tokenCheckInterval: number | null = null

// 监听token变化，管理WebSocket连接
watch(() => userStore.token, (newToken) => {
  if (newToken) {
    // 用户登录，建立WebSocket连接
    wsClient.connect()
  } else {
    // 用户登出，断开WebSocket连接
    wsClient.disconnect()
  }
}, { immediate: true })

// 定期检查token有效性
onMounted(() => {
  // 每分钟检查一次token有效性
  tokenCheckInterval = window.setInterval(() => {
    userStore.checkTokenValidity()
  }, 60000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (tokenCheckInterval) {
    clearInterval(tokenCheckInterval)
  }
})
</script>

<style>
.app {
  min-height: 100vh;
}
</style>
